/*
 * The MIT License
 * 
 * Copyright (c) 2008 Comcast Interactive Media
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package cim.sf.core.command.internal;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import cim.sf.core.command.AnnotatedCommands;
import cim.sf.core.command.CommandInvocation;
import cim.sf.core.command.InvalidUsageException;
import cim.sf.core.command.annotations.Command;

/**
 * @author <a href="mailto:jeremy_volkman@cable.comcast.com">Jeremy Volkman</a>
 */
public class TestCommands implements AnnotatedCommands {

    @Command(path="/.test/echo", description="Echo stdin to stdout",
            usage={"echo [stdout|stderr]"})
    public void echo(CommandInvocation ci) {
        ci.out.println("ECHOING STDIN");
        int bytes = 0;
        OutputStream os = ci.out;
        if (ci.args.length > 0) {
            if ("stdout".equalsIgnoreCase(ci.args[0])) {
                os = ci.out;
            } else if ("stderr".equalsIgnoreCase(ci.args[0])) {
                os = ci.err;
            } else {
                throw new InvalidUsageException("Invalid output stream: " + ci.args[0]);
            }
        }
        try {
            bytes = copyStream(ci.in, os, false);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace(ci.err);
        } finally {
            ci.out.println("FINISHED ECHOING STDIN: " + bytes + " bytes");
        }
    }
    
    @Command(path="/.test/pp", description="Enumerate and print given parameters",
            usage={"pp <param> [param [param...]]"})
    public void printParams(CommandInvocation ci) {
        if (ci.args.length == 0) {
            throw new InvalidUsageException("Must provide arguments");
        }
        for (int i = 1; i <= ci.args.length; i++) {
            ci.out.println(i + ". " + ci.args[i - 1]);
        }
    }

    @Command(path="/.test/sleep", description="Sleep for given amout of milliseconds",
        usage={"sleep <time (ms)>"})
    public void sleep(CommandInvocation ci) {
        if (ci.args.length != 1) {
            throw new InvalidUsageException();
        }
        
        long sleepTime;
        try {
            sleepTime = Long.parseLong(ci.args[0]);
        } catch (NumberFormatException e) {
            throw new InvalidUsageException("Invalid long value: " + ci.args[0]);
        }

        ci.out.printf("Sleeping for %d milliseconds\n", sleepTime);

        try {
            Thread.sleep(sleepTime);
        } catch (InterruptedException e) {
        }
        
        ci.out.println("Finished");
    }
    
    @Command(path="/.test/pwd", description="Print the current working directory",
            usage={"pwd"})
    public void pwd(CommandInvocation ci) {
        if (ci.getCwd() != null) {
            ci.out.println(ci.getCwd());
        } else {
            ci.out.println("Current working directory not available.");
        }
    }

    @Command(path="/.test/return", description="Return the exit status code specified in parameter 1.",
            usage={"return <code>"})
    public int exitStatus(CommandInvocation ci) {
        if (ci.args.length != 1) {
            throw new InvalidUsageException();
        }
        
        int status;
        try {
            status = Integer.parseInt(ci.args[0]);
        } catch (NumberFormatException e) {
            throw new InvalidUsageException("Invalid integer value: " + ci.args[0]);
        }
        ci.out.println("Returning status code: " + status);
        return status;
    }

    private static int copyStream(InputStream in, OutputStream out, boolean closeStreams) throws IOException {
        byte[] buf = new byte[8192];
        int len = 0;
        int copied = 0;
        try {
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
                copied += len;
            }
        } finally {
            if (closeStreams) {
                try { in.close(); } catch (IOException e) {}
                try { out.close();} catch (IOException e) {}
            }
        }
        return copied;
    }
}
